package com.oba.king.sysmanager.area;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.swing.tree.DefaultTreeModel;

import com.oba.base.service.BaseBean;
import com.oba.base.util.TreeUtil;
import com.oba.king.sysmanager.Dept;

public class AreaBean extends BaseBean<Area, AreaService> {

	private DefaultTreeModel tree;
	private Map<Long, Area> areaMap = new HashMap<Long, Area>();
	private Area curArea;
	private Area area;

	private boolean showAddArea = false;
	private List<SelectItem> deptList;
	private Dept dept;

	public Dept getDept() {
		return dept;
	}

	public void setDept(Dept dept) {
		this.dept = dept;
	}

	public List<SelectItem> getDeptList() {
		return deptList;
	}

	public void setDeptList(List<SelectItem> deptList) {
		this.deptList = deptList;
	}

	@Override
	public String doFind() {
		return null;
	}

	public void doAddArea() {
		area = new Area();
		area.setNewBo(true);
		showAddArea = true;
	}

	public void doUpdateArea() {
		area = curArea;
		showAddArea = true;
	}

	public void doDeleteArea() {
		tree.removeNodeFromParent(curArea.getNode());
		getService().getDao().delete(curArea);
		curArea = curArea.getParent();
	}

	public void doSaveArea() {
		if (area.isNewBo()) {
			area.setParent(curArea);
			String serial = getService().getDao().getNextSerial(Area.class, "serial", curArea.getSerial());
			area.setSerial(serial);
			TreeUtil.addChrid(curArea.getNode(), area);
			tree.reload();
		}
		getService().save(area);
		areaMap.put(area.getId(), area);
		showAddArea = false;
		curArea = area;
	}

	public void closeShowAddArea() {
		showAddArea = false;
	}

	public void selectArea() {
		String idStr = getParam("areaId");
		curArea = areaMap.get(Long.parseLong(idStr));
	}

	public void selectDept(ValueChangeEvent e) {
		this.dept = (Dept) e.getNewValue();
	}

	@Override
	public void init() {
		List<Area> list = getService().getDao().findAll();
		curArea = list.get(0);
		for (Area a : list) {
			areaMap.put(a.getId(), a);
		}
		tree = TreeUtil.createTree(list);
		deptList = new ArrayList<SelectItem>();
		List<Dept> dList = getService().getDao().findDeptList();
		for (Dept d : dList) {
			deptList.add(new SelectItem(d, d.getName()));
		}
	}

	public DefaultTreeModel getTree() {
		return tree;
	}

	public void setTree(DefaultTreeModel tree) {
		this.tree = tree;
	}

	public Area getArea() {
		return area;
	}

	public void setArea(Area area) {
		this.area = area;
	}

	public boolean isShowAddArea() {
		return showAddArea;
	}

	public void setShowAddArea(boolean showAddArea) {
		this.showAddArea = showAddArea;
	}

	public Area getCurArea() {
		return curArea;
	}

	public void setCurArea(Area curArea) {
		this.curArea = curArea;
	}

}
